import 'package:cloud_medicine/components/author_show.dart';
import 'package:cloud_medicine/components/util.dart';
import 'package:cloud_medicine/http/config.dart';
import 'package:cloud_medicine/http/prescription_api.dart';
import 'package:cloud_medicine/model/prescription_list.dart';
import 'package:cloud_medicine/pages/prescription_detail.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';

class PreScriptionPage extends StatefulWidget {
  @override
  _PreScriptionPageState createState() => _PreScriptionPageState();
}

class _PreScriptionPageState extends State<PreScriptionPage> {
  bool _loading = false; // 加载状态
  List<PrescriptionItem> _list = [];
  ScrollController _scrollController = ScrollController();
  int _page = 1;

  // 下拉刷新，请求下一页的数据
  Future<Null> _refresh() async {
    _list.clear(); // 清除当前状态数据
    await _loadData();
    Fluttertoast.showToast(
      msg: '刷新成功',
      backgroundColor: Colors.grey[300],
      textColor: Colors.lightBlueAccent,
    );
    return;
  }

  @override
  void initState() {
    super.initState();
    _scrollController.addListener(() {
      if (_scrollController.position.pixels ==
          _scrollController.position.maxScrollExtent) {
        _loadData();
      }
    });
    _loadData();
  }

  // 加载数据
  Future<Null> _loadData() async {
    setState(() {
      _loading = true;
    });
    dynamic res = await getPrescriptionList_api('$backIP/prescription/list', {
      'page': _page,
    });
    res['data'].forEach((dynamic prescriptionItem) {
      PrescriptionItem prescriptionItemModel =
          PrescriptionItem.init(prescriptionItem);
      if (mounted) {
        setState(() {
          _list.add(prescriptionItemModel);
        });
      }
    });
    if (mounted) {
      setState(() {
        _loading = false;
        _page += 1;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.grey[100],
      appBar: AppBar(
        title: Text('处方'),
        centerTitle: true,
        automaticallyImplyLeading: false,
        leading: GestureDetector(
          child: Tooltip(
            child: Icon(Icons.search),
            message: '搜索',
          ),
          onTap: () {
            Navigator.pushNamed(context, '/search');
          },
        ),
      ),
      body: RefreshIndicator(
        onRefresh: _refresh,
        color: Theme.of(context).primaryColor,
        displacement: 40, // 指示器显示时距顶部位置
        child: ListView.builder(
            shrinkWrap: true,
            controller: _scrollController,
            itemCount: _list.length + 1,
            itemBuilder: (context, index) {
              if (index == _list.length) {
                return _loading ? loadingWidget(_loading) : Container();
              } else {
                return Container(
                  margin: EdgeInsets.only(bottom: 10),
                  child: Material(
                    color: Colors.white,
                    child: InkWell(
                      splashColor: Colors.grey.withOpacity(0.3), // 慢慢展开的颜色
                      highlightColor: Colors.grey.withOpacity(0.1), // 高亮颜色
                      onTap: () {
                        Navigator.of(context).push(MaterialPageRoute(
                          builder: (context) => PrescriptionDetailPage(
                            id: _list[index].id,
                          ),
                        ));
                      },
                      child: Container(
                        padding: EdgeInsets.all(8),
                        margin: EdgeInsets.only(bottom: 10),
                        child: new Column(
                          children: <Widget>[
                            AuthorShow(
                              userID: _list[index].authorBasicInfo.id,
                              realname: _list[index].authorBasicInfo.realname,
                              avatar: _list[index].authorBasicInfo.avatar,
                              createTime: _list[index].createTime,
                            ),
                            SizedBox(height: 10),
                            Text(
                              _list[index].abstract,
                              maxLines: 3,
                              overflow: TextOverflow.ellipsis,
                            ),
                            SizedBox(height: 10)
                          ],
                        ),
                      ),
                    ),
                  ),
                );
              }
            }),
      ),
    );
  }
}
